"""
配置管理API路由
提供配置文件的读取、更新和验证功能
"""

from flask import Blueprint, request, jsonify
import logging
from app.config_manager import get_config_manager, ConfigManager
from app.models.system import SystemLog

logger = logging.getLogger(__name__)

config_bp = Blueprint('config', __name__)

@config_bp.route('/status', methods=['GET'])
def get_config_status():
    """获取配置状态和摘要信息"""
    try:
        config_manager = get_config_manager()
        summary = config_manager.get_config_summary()
        
        # 验证配置
        validation_errors = config_manager.validate_config()
        
        result = {
            'summary': summary,
            'validation': {
                'is_valid': len(validation_errors) == 0,
                'errors': validation_errors
            }
        }
        
        SystemLog.log("INFO", "config", "配置状态查询成功")
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"获取配置状态失败: {str(e)}")
        SystemLog.log("ERROR", "config", f"配置状态查询失败: {str(e)}")
        return jsonify({'error': str(e)}), 500

@config_bp.route('/docker', methods=['GET'])
def get_docker_config():
    """获取Docker配置"""
    try:
        config_manager = get_config_manager()
        docker_config = config_manager.get_docker_config()
        
        # 添加计算字段
        registry_url = config_manager.get_registry_url()
        service_images = config_manager.get_service_remote_images()
        
        result = {
            'config': docker_config,
            'computed': {
                'registry_url': registry_url,
                'service_images': service_images,
                'service_count': len(config_manager.get_services_config())
            }
        }
        
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"获取Docker配置失败: {str(e)}")
        return jsonify({'error': str(e)}), 500

@config_bp.route('/docker/services', methods=['GET'])
def get_services_config():
    """获取服务配置列表"""
    try:
        config_manager = get_config_manager()
        services = config_manager.get_services_config()
        
        # 添加完整的镜像URL
        registry_url = config_manager.get_registry_url()
        
        for service in services:
            service['full_remote_image'] = f"{registry_url}/{service['remote_image']}"
        
        return jsonify({'services': services})
        
    except Exception as e:
        logger.error(f"获取服务配置失败: {str(e)}")
        return jsonify({'error': str(e)}), 500 